<template>
  <div class="compact-container">
    <!-- Compact search row with Add button on the right -->
    <div class="search-row">
      <span class="search-label">领料单号：</span>
      <el-input v-model="Picking_outbound_code" size="small" class="search-input" />
      <span class="search-label">仓库编码：</span>
      <el-input v-model="Warehouse_code" size="small" class="search-input" />
      <el-button type="primary" size="small" @click="query">查询</el-button>
      <el-button size="small" @click="reset">重置</el-button>
      <div class="flex-grow"></div>
      <el-button type="primary" size="small" @click="addEdit">添加</el-button>
    </div>

    <el-divider style="margin: 6px 0" />

    <!-- Compact table area -->
    <div class="table-wrapper">
      <el-table 
        :data="flattenedData" 
        border 
        style="width: 100%"
        :cell-style="{ textAlign: 'center', padding: '4px 0' }"
        :header-cell-style="{
          textAlign: 'center',
          background: '#f5f7fa',
          fontWeight: 'bold',
          position: 'sticky',
          top: 0,
          padding: '4px 0',
          height: '36px'
        }"
        :row-style="{ height: '36px' }"
        :span-method="objectSpanMethod"
        v-loading="loading"
      >
        <!-- Table columns -->
        <el-table-column fixed width="180px" prop="picking_outbound_code" label="领料单号">
          <template #default="scope">
            <el-link type="primary" @click="infoPage(scope.row)">{{ scope.row.picking_outbound_code }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="picking_outbound_status" label="出库状态" width="100px">
          <template #default="{row}">{{ getStatusText(row.picking_outbound_status) }}</template>
        </el-table-column>
        <el-table-column prop="picking_outbound_audit_status" label="审核状态" width="100px">
          <template #default="{row}">
            {{ row.picking_outbound_audit_status === '1' ? '已审核' : row.picking_outbound_audit_status === '2' ? '驳回' : '未审核' }}
          </template>
        </el-table-column>
        <el-table-column prop="warehouse_code" label="仓库编码" width="150px"/>
        <el-table-column prop="zone_code" label="库区编码" width="150px" />
        <el-table-column prop="picking_outbound_rep_id" label="拣货人" width="120px">
          <template #default="scope">{{ userValue(scope.row.picking_outbound_rep_id) }}</template>
        </el-table-column>
        <el-table-column prop="pro_name" width="150px" label="产品名称" />
        <el-table-column prop="pro_code" width="180px" label="产品编码"/>
        <el-table-column prop="picking_outbound_qty" width="120px" label="待出库数量" align="right" />
        <el-table-column prop="picking_for_outbound_qty" width="120px" label="出库数量" align="right" />
        <el-table-column prop="qty" width="120px" label="总计出库数量" align="right">
          <template #default="scope">{{ zjValue(scope.row) }}</template>
        </el-table-column>
        <el-table-column prop="caozuo" fixed="right" label="操作" width="180px">
          <template #default="scope">
            <div class="action-group">
              <el-button size="small" :disabled="scope.row.picking_outbound_audit_status === '1' || scope.row.picking_outbound_audit_status === '2'" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button size="small" :disabled="scope.row.picking_outbound_audit_status === '1' || scope.row.picking_outbound_audit_status === '2'" type="warning" @click="handleAudit(scope.row)">审核</el-button>
              <el-button size="small" :disabled="scope.row.picking_outbound_audit_status === '1' || scope.row.picking_outbound_audit_status === '2'" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- Centered pagination -->
      <div class="pagination-center">
        <el-pagination
          small
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageCount"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
  <el-dialog v-model="centerDialogVisible" width="385" align-center header-align="left">
    <template #header>
      <div style="text-align: left; font-size: 16px; font-weight: bold;">
        审核
      </div>
    </template>
    <hr>
    <div style="text-align: left;padding: 10px 0px;">
      <p>审核结果</p>
      <div class="my-2 ml-4">
        <el-radio-group v-model="auditStatus">
          <el-radio value="1">通过</el-radio>
          <el-radio value="2">驳回</el-radio>
        </el-radio-group>
      </div>
    </div>
    <hr>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="updateAudit">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import axios from 'axios'
import dayjs from 'dayjs';
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router';
import { ref, onMounted, markRaw } from 'vue';
import { Delete } from '@element-plus/icons-vue'
import { useStore } from 'vuex';

export default {
  setup() {
    const store = useStore();
    const datamax = store.state.PO_UpdeteArray

    const centerDialogVisible = ref(false);
    const auditStatus = ref('1');
    const fg_audit_id = ref(0);
    const currentPickingCode = ref(''); // 新增：存储当前审核的领料单号

    const Router = useRouter();
    const tableData = ref([]);
    const flattenedData = ref([]);
    const spanArr = ref([]);
    const Picking_outbound_code = ref('');
    const Warehouse_code = ref('');
    const currentPage = ref(1);
    const pageSize = ref(10);
    const pageCount = ref(0);
    const loading = ref(false);
    const warehouseData = ref([]);
    const userOptions = ref([]);

    const getStatusText = (status) => {
      switch(status) {
        case '0': return '待出库';
        case '1': return '全部出库';
        default: return '未知状态';
      }
    }

    onMounted(() => {
      fill();
      count();
      getUser();
    });
    
    function getUser() {
      axios.get("http://localhost:5181/api/User/GetUsers", {
        headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
      }).then((result) => {
        userOptions.value = result.data;
      }).catch((err) => {
        console.error(err);
      });
    }
    
    function userValue(row) {
      if (!row) return "无";
      const user = userOptions.value.find((u) => u.user_id == row);
      return user ? user.user_name : "无";
    }
    
    const processData = (data) => {
      const flatData = [];
      spanArr.value = [];
      
      data.forEach(order => {
        const mainOrder = {
          ...order,
          pro_name: '',
          pro_code: '',
          pro_attribute_id: '',
          picking_outbound_qty: '',
        };
        
        const rowCount = order.details ? order.details.length : 1;
        spanArr.value.push(rowCount);
        
        if (order.details && order.details.length > 0) {
          order.details.forEach(detail => {
            flatData.push({ ...mainOrder, ...detail });
          });
        } else {
          flatData.push(mainOrder);
        }
      });
      
      return flatData;
    }

    const formatDate = (dateString) => {
      if (!dateString) return '';
      const date = new Date(dateString);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
    }

    const fill = () => {
      loading.value = true;
      axios.get("http://localhost:5181/api/FG_Picking_Outbound/GetFG_Picking_OutboundFYwhere", {
        params: {
          Picking_outbound_code: Picking_outbound_code.value,
          Warehouse_code: Warehouse_code.value,
          currentPage: currentPage.value,
          pageSize: pageSize.value
        },
        headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
      }).then((res) => {
        const formattedData = res.data.map(item => ({
          ...item,
          picking_outbound_audit_time: formatDate(item.picking_outbound_audit_time),
          create_time: formatDate(item.create_time),
          update_time: formatDate(item.update_time),
          picking_outbound_time: formatDate(item.picking_outbound_time),
        }));
        
        tableData.value = formattedData;
        flattenedData.value = processData(formattedData);
      }).catch((err) => {
        console.error('数据加载失败', err);
        ElMessage.error('数据加载失败');
      }).finally(() => {
        loading.value = false;
      });
    }

    const objectSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
      const mergeColumns = [
        'picking_outbound_code', 'picking_outbound_status', 
        'picking_outbound_audit_status', 'warehouse_code', 
        'zone_code', 'picking_outbound_rep_id', 'operation',
        'qty','caozuo'
      ];
      
      if (mergeColumns.includes(column.property)) {
        let position = 0;
        for (let i = 0; i < spanArr.value.length; i++) {
          const count = spanArr.value[i];
          if (rowIndex < position + count) {
            return {
              rowspan: rowIndex === position ? count : 0,
              colspan: 1
            };
          }
          position += count;
        }
      }
    }

    function zjValue(row) {
      let total = 0;
      const mainOrder = tableData.value.find(
        item => item.picking_outbound_code === row.picking_outbound_code
      );
      if (mainOrder && mainOrder.details && Array.isArray(mainOrder.details)) {
        mainOrder.details.forEach(detail => {
          total += Number(detail.picking_for_outbound_qty || 0);
        });
      }
      return total;
    }

    const count = () => {
      axios.get("http://localhost:5181/api/FG_Picking_Outbound/GetFG_Picking_OutboundCount", {
        params: {
          Picking_outbound_code: Picking_outbound_code.value,
          Warehouse_code: Warehouse_code.value,
        },
        headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
      }).then((res) => {
        pageCount.value = res.data;
      }).catch((err) => {
        console.error('总条数加载失败', err);
        ElMessage.error('总条数加载失败');
      });
    }

    const query = () => {
      currentPage.value = 1;
      fill();
      count();
    }

    function infoPage(row) {
      store.commit('PO_UpdeteArray', row)
      Router.push({
        path: '/main/FG/PickingInfo',
        // query: { rowData: JSON.stringify(row) }
      });
    }

    const reset = () => {
      Picking_outbound_code.value = '';
      Warehouse_code.value = '';
      query();
    }

    const addEdit = () => {
      Router.push({ path: '/main/FG/PickingAdd' });
    }

    const handleEdit = (row) => {
      if(row.picking_outbound_audit_status > '0') {
        ElMessage.error("已审核后的领料单不可编辑");
      } else {
        store.commit('PO_UpdeteArray', row)
        Router.push({
          path: '/main/FG/PickingUpdate',
          // query: { rowData: JSON.stringify(row) }
        });
      }
    }

    function handleDelete(row) {
      if(row.picking_outbound_audit_status > '0') {
        ElMessage.error("已审核后的领料单不可删除");
      } else {
        ElMessageBox.confirm(
          '此操作将删除该领料单信息，是否继续？',
          '警告',
          {
            type: 'warning',
            icon: markRaw(Delete),
            confirmButtonText: '确定',
            cancelButtonText: '取消',
          }
        )
        .then(() => {
          return axios.put('http://localhost:5181/api/FG_Picking_Outbound/PutFG_Picking_OutboundDelete', {
            picking_outbound_id: row.picking_outbound_id,
            del_flag: "1"
          }, {
            headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
          });
        })
        .then((result) => {
          if (result.data > 0) {
            ElMessage.success("删除成功");
            fill();
            count();
          } else {
            ElMessage.error("删除失败");
          }
        })
        .catch((error) => {
          console.error("删除失败:", error);
        });
      }
    }

    const handleSizeChange = (val) => {
      pageSize.value = val;
      fill();
    }
    
    const handleCurrentChange = (val) => {
      currentPage.value = val;
      fill();
    }

    function handleAudit(row){
      fg_audit_id.value = row.picking_outbound_id;
      currentPickingCode.value = row.picking_outbound_code; // 保存当前领料单号
      centerDialogVisible.value = true;
    }

    function updateAudit() {
      // 构建主表数据
      const FG_Picking_Outbound_AuditDto = {
        Picking_outbound_id: fg_audit_id.value,
        Picking_outbound_audit_by: localStorage.getItem('userLName'),
        Picking_outbound_audit_time: dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ'),
        Picking_outbound_audit_status: auditStatus.value
      };
      
      // 只筛选当前领料单的明细数据
      const fg_Picking_Outbound_DetailsAuditDtos = flattenedData.value
        .filter(d => d.picking_outbound_code === currentPickingCode.value)
        .map(d => ({
          Picking_outbound_id: d.picking_outbound_id,
          Picking_for_outbound_qty: d.picking_for_outbound_qty,
          Picking_outbound_qty: d.picking_outbound_qty,
          Location_code: d.location_code,
          Picking_outbound_code: d.picking_outbound_code,
          Picking_outbound_details_id: d.picking_outbound_details_id,
          pro_code: d.pro_code
        }));
      
      // 构建符合后端期望的DTO结构
      const requestData = {
        FG_Picking_Outbound_AuditDto: FG_Picking_Outbound_AuditDto,
        fg_Picking_Outbound_DetailsAuditDtos: fg_Picking_Outbound_DetailsAuditDtos
      };
      console.log(requestData);
      // 调用审核API
      axios.put("http://localhost:5181/api/FG_Picking_Outbound/PutFg_Picking_OutboundAudit", requestData, {
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                if (result.data > 0) {
                    ElMessage.success('领料出库单审核成功！');
                    close();
                    query()
                }
                centerDialogVisible.value = false
            }).catch((err) => {
                console.error(err)
                ElMessage.error('审核失败');
            });
    }

    function close() {
      centerDialogVisible.value = false;
      auditStatus.value = '1';
    }

    return {
      tableData,
      flattenedData,
      Picking_outbound_code,
      Warehouse_code,
      currentPage,
      pageSize,
      pageCount,
      loading,
      warehouseData,
      userOptions,
      centerDialogVisible,
      auditStatus,
      fg_audit_id,
      handleAudit,
      query,
      reset,
      addEdit,
      handleEdit,
      handleDelete,
      handleSizeChange,
      handleCurrentChange,
      objectSpanMethod,
      getStatusText,
      userValue,
      infoPage,
      zjValue,
      updateAudit,
      close
    }
  }
}
</script>

<style scoped>
.compact-container {
  padding: 10px;
  margin-top: -10px;
}

.search-row {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-bottom: 6px;
  margin-top: -40px;
}

.search-label {
  white-space: nowrap;
  font-size: 13px;
}

.search-input {
  width: 160px !important;
}

.flex-grow {
  flex-grow: 1;
}

.table-wrapper {
  margin-top: 6px;
}

:deep(.el-table__row) {
  height: 36px !important;
}

:deep(.el-table th.el-table__cell) {
  height: 36px !important;
}

:deep(.el-button--small) {
  padding: 5px 8px;
  height: 24px;
}

.pagination-center {
  display: flex;
  justify-content: center;
  margin-top: 8px;
}

.action-group {
  display: flex;
  justify-content: center;
  gap: 4px;
}
</style>